# -*- coding: utf-8 -*- 
# @Time : 2021/6/16 16:43 
# @Author : Orange
# @File : trainer.py.py
# -*- coding: utf-8 -*-

from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
from xgboost import XGBRegressor
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
import pandas as pd
from 排气温度.data_processing import *
from 排气温度.get_data import get_iv_data
import datetime
from 排气温度.algorithm import call
from 排气温度.algorithm import *
def train(*args, **kwargs):
    yesterday = (datetime.datetime.now() + datetime.timedelta(days=-1)).date().strftime('%Y-%m-%d')
    train_end_time = yesterday + " 23:00:00"
    params = {"param":
        {
            "domain": "EMS",
            "equip_id": "ECR12",
            "equip_mk": "ECR",
            "station_id": "PARK569_EMS01",
            "start_time": "2020-01-01 00:00:00",
            "end_time": train_end_time

        }
    }
    param = params.get('param')
    #mm,param = call()
    # helper = kwargs.get('helper')
    #

    # # 更新模型描述信息
    # helper.update_model_desc('用于回归的xgb模型')
    data = get_iv_data(start_time=param['start_time'], end_time=param['end_time'], equip_id=param['equip_id'],
                       station_id=param['station_id'], equip_mk=param['equip_mk'])
    data_1, data_p0 = data_processing(data)
    x = data_1.loc[:, ['TchwOut', 'TchwIn', 'TcwOut', 'IratioCpr', 'Pelec', 'TcwIn']]
    y = data_1['TcprAirOut']
    x_train = x.iloc[::]
    y_train = y[::]
    # 这是时间序列的测试集和训练集分割函数
    my_cv = TimeSeriesSplit(n_splits=2).split(x_train)
    cv_params = {'min_child_weight': [1, 2, 3, 4, 5, 6, 7]}
    other_params = {'learning_rate': 0.1, 'n_estimators': 1000, 'max_depth': 4, 'min_child_weight': 2, 'seed': 0,
                    'subsample': 0.8, 'colsample_bytree': 0.9, 'gamma': 0, 'reg_alpha': 0.1, 'reg_lambda': 2}
    model = XGBRegressor(**other_params)
    optimized_GBM = GridSearchCV(estimator=model, param_grid=cv_params, scoring='r2', cv=my_cv, verbose=1, n_jobs=4)
    optimized_GBM.fit(np.array(x_train), np.array(y_train))
    model = optimized_GBM.best_estimator_
    return model



params = {"param":
    {
        "domain": "EMS",
        "equip_id": "ECR12",
        "equip_mk": "ECR",
        "station_id": "PARK569_EMS01",
        "start_time": "2021-06-15 14:00:00",
        "end_time": "2021-06-16 14:00:00"

    }
}
model = train(**params)
print("model:",model)
# y_hat = model.predict(np.array(x_train))
# y_hat = pd.Series(y_hat, index=y_test.index)
# print(y_hat, y_test)
# # 性能评价  R^2越小越好，最优值为1
# mse = mean_squared_error(y_test, y_hat)  # ((y_test-y_hat)**2).mean()
# print('MSE', mse)
# r_2 = r2_score(y_test, y_hat)
# print('r^2', r_2)
